package com.bayihouse.utils;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.UUID;

public class MyFileUtils {

    public static <T> void saveFile(String filePath, String fileName, T t) {
        if (!(StringUtils.isNotBlank(fileName) && StringUtils.isNotBlank(filePath))) {
            throw new RuntimeException("文件路径和文件名不能为空");
        }
        ObjectOutputStream objectOutputStream = null;
        try {
            if (!FileUtil.exist(filePath)) {
                FileUtil.mkdir(filePath);
            }
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath + File.separator + fileName));
            objectOutputStream.writeObject(t);
            objectOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static <T> T readFile(String filePath, String fileName) {
        ObjectInputStream objectInputStream = null;
        T t = null;
        try {
            objectInputStream = new ObjectInputStream(new FileInputStream(filePath + File.separator + fileName));
            t = (T) objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return t;
    }


    public static <T> T readFile(InputStream inputStream) {
        ObjectInputStream objectInputStream = null;
        T t = null;
        try {
            objectInputStream = new ObjectInputStream(inputStream);
            t = (T) objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return t;
    }
}
